'use strict';
// 侧边导航
const Controller = require('egg').Controller;

class NavController extends Controller {
  async edit() {
      const { ctx, app } = this
      const { id, text, path, name, component } = ctx.request.body
      ctx.validate({
          text: {
              type: 'string',
              required: true,
              desc: '名称'
          },
          path: {
              type: 'string',
              required: true,
              desc: '路径'
          },
          name: {
              type: 'string',
              required: true,
              desc: '标题'
          },
          component: {
              type: 'string',
              required: true,
              desc: '关键词'
          },
      })
      let oneList, twoList
      if (id == 0) {//新建
          twoList = await app.model.AdminNav.create({
              text, path, name, component
          })
      } else {//编辑
          oneList = await app.model.AdminNav.findByPk(id)
          if (!oneList) {
              ctx.throw(400, '数据不存在')
          }
          twoList = await oneList.update({ text, path, name, component })
      }
      ctx.apiSuccess(twoList)
    }
    async list() {
        const { ctx, app }=this
        let text = ctx.query.text
        let where = {}
        let Op = app.Sequelize.Op;
        if (text != "" && text != undefined) {
            where = {
                text:{
                    [Op.like]:'%'+ text +'%'
                }
            }
        }
        let oneList = await ctx.page(app.model.AdminNav, where)
        
        ctx.apiSuccess(oneList)
    }
    async del() {
        const { ctx, app } = this
        ctx.validate({
            id: {
                type: 'int',
                required: true,
                desc: 'id'
            }
        })
        let id = ctx.query.id
        let oneList = await app.model.AdminNav.findByPk(id)
        if (!oneList) {
            ctx.throw(400, '数据不存在')
        }
        oneList = await oneList.destroy()
        if (!oneList) {
            ctx.throw(400, '操作失败')
        }
        ctx.apiSuccess('删除成功')
    }
}

module.exports = NavController;
